#!/bin/bash
#author 51yuki
#date 2018-01-11
#description  source code install nginx server
SoftDir="/usr/local/src"
User="nginx"
Version=$1
InstallDir="/data/application"
LogDir="/data/logs"
CacheDir="/var/cache/nginx"
SystemVer=$(cat /etc/centos-release|awk -F' ' '{if(NR==1) print $4}'|cut -d. -f1)


if [ $# -ne 1 ];then
        echo "Usage:$0 <Nginx-Version>"
        exit 0
fi

[ ! -d $SoftDir ] && mkdir -p $SoftDir
[ ! -d $InstallDir ] && mkdir -p $InstallDir
[ ! -d $LogDir ] && mkdir -p $LogDir


if ! id $User &>/dev/null ;then
	groupadd -g 3001 -r nginx
	useradd -u 3001 -g nginx -s /sbin/nologin -r nginx
fi

[ ! -d $CacheDir ] && mkdir -p $CacheDir && mkdir nginx.nginx -R $CacheDir 
# Install dependency software

rm -rf /var/run/yum.pid && yum -y install pcre-devel zlib-devel openssl-devel geoip-devel gd-devel  pcre

# install nginx

function install_nginx() {
	cd $SoftDir
	wget http://nginx.org/download/nginx-${Version}.tar.gz
	tar zxf nginx-${Version}.tar.gz
	cd nginx-${Version}
	./configure --prefix=${InstallDir}/nginx-${Version} --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp  --user=nginx --group=nginx --with-file-aio --with-threads  --with-http_addition_module --with-http_auth_request_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_realip_module --with-http_secure_link_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module  --with-stream --with-stream_ssl_module  --with-http_image_filter_module --with-pcre 
	make && make install
}
install_nginx

ln -s /data/application/nginx-${Version} /data/application/nginx

# modify nginx configure file
cp /data/application/nginx/conf/nginx.conf{,.ori}
vim ${InstallDir}/nginx/conf/nginx.conf <<VIM > /dev/null 2>&1
:%s/worker_processes  1;/worker_processes  auto;/
:%s/worker_connections  1024;/worker_connections  4096;/
:%s/#gzip/server_tokens off;\r    gzip/
:%s/#gzip/gzip/
:wq
VIM

sed -i "/gzip  on;/a \
     include /data/application/nginx-${Version}/conf.d/*.conf;" /data/application/nginx/conf/nginx.conf

if [ "${SystemVer}" == "6" ];then
	cd $SoftDir	
	wget -q https://gitee.com/louis1986/shell_scripts/raw/master/web/nginx/source/nginx
	cd /etc/init.d && [ -f nginx ] && mv nginx nginx.ori && cp ${SoftDir}/nginx /etc/init.d/nginx
	chmod u+x /etc/init.d/nginx
	chkconfig --add nginx
	chkconfig nginx on
	service nginx start
fi

if [ "${SystemVer}" == "7" ];then
	cd $SoftDir
	wget -q https://gitee.com/louis1986/shell_scripts/raw/master/web/nginx/source/nginx.service
	cd /usr/lib/systemd/system && [ -f nginx.service ] && mv nginx.service nginx.service.ori && cp ${SoftDir}/nginx.service /usr/lib/systemd/system/nginx.service
	systemctl enable nginx.service
	systemctl start nginx.service
fi

